package com.example.rocketmq.demo.config;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;

/**
 * RocketMQ 注解支持配置类
 */
@Configuration
public class RocketMQAnnotationConfig {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    /**
     * 创建 RocketMQTemplate 用于注解方式发送消息
     * 注意：实际上RocketMQ Spring Boot Starter会自动创建RocketMQTemplate
     * 这里是为了演示如何手动配置
     */
    @Bean
    public RocketMQTemplate rocketMQAnnotationTemplate() {
        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();

        DefaultMQProducer producer = new DefaultMQProducer();
        producer.setProducerGroup(producerGroup + "-annotation");
        producer.setNamesrvAddr(nameServer);
        producer.setVipChannelEnabled(false);
        producer.setRetryTimesWhenSendAsyncFailed(3);
        producer.setRetryTimesWhenSendFailed(3);
        producer.setSendMsgTimeout(3000);

        rocketMQTemplate.setProducer(producer);

        // 设置消息转换器
        rocketMQTemplate.setMessageConverter(rocketMQMessageConverter());

        return rocketMQTemplate;
    }

    /**
     * 创建消息转换器，用于将Java对象转换为消息
     */
    @Bean
    @ConditionalOnMissingBean
    public MessageConverter rocketMQMessageConverter() {
        return new RocketMQMessageConverter().getMessageConverter();
    }
}
